package com.easylinkin.linkappapi.weather.controller;

import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.sevice.LinkappTenantService;
import com.easylinkin.linkappapi.weather.entity.WeatherRecord;
import com.easylinkin.linkappapi.weather.job.WeatherTask;
import com.easylinkin.linkappapi.weather.service.WeatherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 天气控制器
 */
@RestController
@RequestMapping("/api/weather")
@Api(tags = "天气管理")
@Slf4j
public class WeatherController {

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private WeatherTask weatherTask;

    @Autowired
    private LinkappTenantService tenantService;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    /**
     * 查询当前用户的天气历史记录
     */
    @GetMapping("/history")
    @ApiOperation("查询天气历史记录")
    public RestMessage getWeatherHistory(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        
        // 获取当前登录用户
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        if (currentUser == null) {
            return RestBuilders.failureBuilder().message("用户未登录").build();
        }
        
        if (StringUtils.isBlank(currentUser.getTenantId())) {
            return RestBuilders.failureBuilder().message("用户未绑定租户").build();
        }
        
        try {
            List<WeatherRecord> records = weatherService.getHistoryRecords(
                currentUser.getTenantId(), startTime, endTime);
            return RestBuilders.successBuilder().data(records).build();
        } catch (Exception e) {
            log.error("查询天气历史记录失败", e);
            return RestBuilders.failureBuilder().message("查询失败").build();
        }
    }

    /**
     * 获取当前用户最新的天气信息
     */
    @GetMapping("/latest")
    @ApiOperation("获取最新天气信息")
    public RestMessage getLatestWeather() {
        // 获取当前登录用户
        LinkappUser currentUser = linkappUserContextProducer.getCurrent();
        if (currentUser == null) {
            return RestBuilders.failureBuilder().message("用户未登录").build();
        }
        
        if (StringUtils.isBlank(currentUser.getTenantId())) {
            return RestBuilders.failureBuilder().message("用户未绑定租户").build();
        }
        
        try {
            WeatherRecord latestRecord = weatherService.getLatestRecord(currentUser.getTenantId());
            if (latestRecord == null) {
                return RestBuilders.failureBuilder().message("暂无天气数据").build();
            }
            return RestBuilders.successBuilder().data(latestRecord).build();
        } catch (Exception e) {
            log.error("获取最新天气信息失败", e);
            return RestBuilders.failureBuilder().message("获取失败").build();
        }
    }

    /**
     * 手动触发天气数据获取
     */
    @PostMapping("/manual-fetch")
    @ApiOperation("手动触发天气数据获取")
    public RestMessage manualFetchWeather() {
        try {
            weatherTask.manualFetchWeatherData();
            return RestBuilders.successBuilder().message("天气数据获取任务已触发").build();
        } catch (Exception e) {
            log.error("手动触发天气数据获取失败", e);
            return RestBuilders.failureBuilder().message("触发失败").build();
        }
    }

    /**
     * 根据租户ID查询天气历史记录（管理员功能）
     */
    @GetMapping("/history/{tenantId}")
    @ApiOperation("根据租户ID查询天气历史记录")
    public RestMessage getWeatherHistoryByTenantId(
            @PathVariable String tenantId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        
        // 验证租户是否存在
        LinkappTenant tenant = tenantService.getById(tenantId);
        if (tenant == null) {
            return RestBuilders.failureBuilder().message("租户不存在").build();
        }
        
        try {
            List<WeatherRecord> records = weatherService.getHistoryRecords(tenantId, startTime, endTime);
            return RestBuilders.successBuilder().data(records).build();
        } catch (Exception e) {
            log.error("查询租户{}天气历史记录失败", tenantId, e);
            return RestBuilders.failureBuilder().message("查询失败").build();
        }
    }

    /**
     * 测试天气API连接
     */
    @GetMapping("/test")
    @ApiOperation("测试天气API接口")
    public RestMessage testWeatherApi() {
        try {
            // 使用北京的坐标进行测试
            weatherService.fetchAndSaveWeather(116.39, 39.90, "test-tenant");
            return RestBuilders.successBuilder().message("天气API测试成功，已使用Unirest HTTP客户端").build();
        } catch (Exception e) {
            log.error("天气API测试失败", e);
            return RestBuilders.failureBuilder().message("测试失败: " + e.getMessage()).build();
        }
    }
} 